const http = require('http');

function makeRequest(options, data = null) {
    return new Promise((resolve, reject) => {
        const req = http.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                try {
                    const jsonBody = body ? JSON.parse(body) : {};
                    resolve({ status: res.statusCode, data: jsonBody, body });
                } catch (e) {
                    resolve({ status: res.statusCode, data: null, body });
                }
            });
        });

        req.on('error', reject);
        
        if (data) {
            req.write(data);
        }
        
        req.end();
    });
}

async function testSongDataUpload() {
    console.log('🎵 测试歌名和原唱数据存储...');
    
    const baseOptions = {
        hostname: 'localhost',
        port: 3001,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    try {
        // 准备测试数据
        const testSongName = '我的新歌曲-' + Date.now();
        const testArtistName = '我的新歌手-' + Date.now();
        
        console.log('\n📝 准备测试数据:');
        console.log('歌名:', testSongName);
        console.log('原唱:', testArtistName);

        // 1. 先添加歌手
        console.log('\n1️⃣ 添加歌手到数据库...');
        const addArtistResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'POST'
        }, JSON.stringify({ name: testArtistName }));
        
        console.log('添加歌手结果:', addArtistResult);

        if (addArtistResult.status === 200 && addArtistResult.data?.success) {
            const artistId = addArtistResult.data.data.id;
            console.log('✅ 歌手添加成功，ID:', artistId);

            // 2. 添加歌曲
            console.log('\n2️⃣ 添加歌曲到数据库...');
            const addSongResult = await makeRequest({
                ...baseOptions,
                path: '/api/songs',
                method: 'POST'
            }, JSON.stringify({ name: testSongName }));
            
            console.log('添加歌曲结果:', addSongResult);

            if (addSongResult.status === 200 && addSongResult.data?.success) {
                const songId = addSongResult.data.data.id;
                console.log('✅ 歌曲添加成功，ID:', songId);

                // 3. 验证数据是否正确存储
                console.log('\n3️⃣ 验证数据存储...');
                
                // 检查歌手列表
                const artistsResult = await makeRequest({
                    ...baseOptions,
                    path: '/api/songers',
                    method: 'GET'
                });
                
                console.log('当前歌手数量:', artistsResult.data?.data?.length || 0);
                
                // 检查歌曲列表
                const songsResult = await makeRequest({
                    ...baseOptions,
                    path: '/api/songs',
                    method: 'GET'
                });
                
                console.log('当前歌曲数量:', songsResult.data?.data?.length || 0);
                
                // 查找我们刚添加的数据
                const ourArtist = artistsResult.data?.data?.find(a => a.name === testArtistName);
                const ourSong = songsResult.data?.data?.find(s => s.title === testSongName);
                
                console.log('\n📊 验证结果:');
                console.log('找到我们的歌手:', ourArtist ? '✅' : '❌');
                console.log('找到我们的歌曲:', ourSong ? '✅' : '❌');
                
                if (ourArtist && ourSong) {
                    console.log('\n🎉 测试完全成功！');
                    console.log('歌手信息:', { id: ourArtist.id, name: ourArtist.name });
                    console.log('歌曲信息:', { id: ourSong.id, title: ourSong.title, artist: ourSong.artist });
                } else {
                    console.log('\n⚠️ 数据存储可能有问题');
                }
                
            } else {
                console.log('❌ 歌曲添加失败');
            }
        } else {
            console.log('❌ 歌手添加失败');
        }

    } catch (error) {
        console.error('❌ 测试失败:', error);
    }
}

testSongDataUpload().then(() => {
    console.log('\n🏁 歌名和原唱数据存储测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});